package com.zx.crowdfunding.mvc.handler;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zx.crowdfunding.entity.Operation;
import com.zx.crowdfunding.global.CrowdFundingGlobal;
import com.zx.crowdfunding.service.api.AuthService;
import com.zx.crowdfunding.service.api.OperationService;
import com.zx.crowdfunding.util.ResultEntity;

/**
 * 操作 - Handler
 * @author 郑雪
 * @date 2021-12-15
 */
@RestController
public class OperationHandler {

	/**
	 * 操作Service接口
	 */
	@Autowired
	private OperationService operationService;
	
	/**
	 * 权限Service接口
	 */
	@Autowired
	private AuthService authService;
	
	/**
	 * 查询操作树形结构
	 * @return JSON数据
	 */
	@RequestMapping("/operation/get/tree.json")
	public ResultEntity<List<Operation>> getTree(){
		
		// 查询全部的Operation对象
		List<Operation> list = operationService.getAll();
		
		// 返回JSON数据
		return ResultEntity.successWithData(list);
	}
	
	/**
	 * 添加操作
	 * @param operation 操作对象
	 * @return JSON数据
	 */
	@RequestMapping("/operation/save.json")
	public ResultEntity<String> save(Operation operation, HttpServletRequest request){
		
		// 执行添加
		operationService.saveOperation(operation);
		
		// 获取Servlet上下文
		ServletContext servletContext = request.getSession().getServletContext();
		
		// 更新全局静态变量和Application域中的值
		authService.updateGlobalCodeAuth(servletContext);
		
		// 返回JSON数据
		return ResultEntity.successWithoutData();
	}
	
	/**
	 * 修改操作
	 * @param operation 操作对象
	 * @return JSON数据
	 */
	@RequestMapping("/operation/edit.json")
	public ResultEntity<String> edit(Operation operation, HttpServletRequest request){
		
		// 执行修改
		operationService.editOperation(operation);
		
		// 设置全局静态变量需要更新，为了通知SpringSecurity的权限授权数据源下次使用时需重新加载
		CrowdFundingGlobal.UPDATE_RESOURCE_AUTH = true;
		
		// 获取Servlet上下文
		ServletContext servletContext = request.getSession().getServletContext();
		
		// 更新全局静态变量和Application域中的值
		authService.updateGlobalCodeAuth(servletContext);
		
		// 返回JSON数据
		return ResultEntity.successWithoutData();
	}
	
	/**
	 * 删除操作
	 * @param idList 操作id的List集合
	 * @return JSON数据
	 */
	@RequestMapping("/operation/remove.json")
	public ResultEntity<String> remove(@RequestBody List<Integer> idList, HttpServletRequest request){
		
		// 执行删除
		operationService.removeOperation(idList);
		
		// 获取Servlet上下文
		ServletContext servletContext = request.getSession().getServletContext();
		
		// 更新全局静态变量和Application域中的值
		authService.updateGlobalCodeAuth(servletContext);
		
		// 返回JSON数据
		return ResultEntity.successWithoutData();
	}
}
